<template>
  <div class="relative overflow-hidden" :style="{ width: width + 'px', height: height + 'px' }">
    <div
      class="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2"
      :class="[isError ? '' : 'cursor-pointer']"
      @click="preview"
    >
      <img
        ref="imgEl"
        class="block"
        :style="[imgWidth ? { width: imgWidth + 'px' } : {}, imgHeight ? { height: imgHeight + 'px' } : {}]"
        :src="innerSrc"
        @load="handleLoad"
        @error="handleError"
      />
    </div>
    <a-image
      :style="{ display: 'none' }"
      :preview="{
        visible,
        onVisibleChange: setVisible,
      }"
      :src="src"
    />
  </div>
</template>
<script setup lang="ts">
import { ref, watch } from "vue";

const props = defineProps<{
  width: number;
  height: number;
  src: string;
}>();
const innerSrc = ref(props.src);
const visible = ref(false);
const imgWidth = ref(props.width);
const imgHeight = ref(0);
const setVisible = (value): void => {
  visible.value = value;
};

const imgEl = ref<HTMLImageElement>();
function handleLoad() {
  if (imgEl.value) {
    if (isError.value) {
      return;
    }
    const curHeight = imgEl.value.offsetHeight;
    if (curHeight < props.height) {
      imgWidth.value = 0;
      imgHeight.value = props.height;
    }
  }
}
function handleError() {
  isError.value = true;
  innerSrc.value = "/project_logo.png";
  imgWidth.value = props.width;
  imgHeight.value = props.width;
}

const isError = ref(false);
watch(
  () => props.src,
  (v) => {
    isError.value = false;
    innerSrc.value = v;
  }
);

function preview() {
  if (isError.value) return;
  setVisible(true);
}
</script>
